package demo;

import java.io.FileInputStream;
import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

public class RSAKeyPairFileReader {
    public static void main(String[] args) throws Exception {
// 从文件中读取公钥和私钥
        byte[] publicKeyBytes = readFromFile("./key/publicKey.pub");
        byte[] privateKeyBytes = readFromFile("./key/privateKey.pri");

// 将公钥和私钥还原为Java对象
        PublicKey publicKey = KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(publicKeyBytes));
        PrivateKey privateKey = KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(privateKeyBytes));

// 验证读取结果
        System.out.println("Public key: " + new String(publicKey.getEncoded(), StandardCharsets.UTF_8));
        System.out.println("Private key: " + new String(privateKey.getEncoded(), StandardCharsets.UTF_8));
    }


    private static byte[] readFromFile(String fileName) throws Exception {
        try (FileInputStream inputStream = new FileInputStream(fileName)) {
            byte[] buffer = new byte[inputStream.available()];
            inputStream.read(buffer);
            return buffer;
        }
    }
}
